'''
json.loads():解析一个有效的JSON字符串并将其转换为Python对象(Python字典)
json.load():从一个文件读取JSON类型的数据,然后转转换成Python对象(Python字典)
json.dump:主要用来将python对象(字典)写入json文件
json.dumps:将python对象格式(字典)化成json字符
'''

import ujson

cfgpath= "/cfg.json"
global cfg_data
    
def read_cfg_data():
    global cfg_data
    cfg_data = read_cfg()
    return cfg_data

def read_cfg():
    result={}
    with open(cfgpath,'r') as f:
        json_data=ujson.load(f)
    #print("json_data",json_data)

    # 透传模式
    result["name"]=json_data["name"]
    result["timestamp"]=json_data["timestamp"]
    result["hearttime"]=json_data["hearttime"]
    result["triad"]=json_data["triad"]                                       
    return result            

def write_cfg(data):
    with open(cfgpath,'r') as fr:
        json_data = ujson.load(fr)

    if "name" in data :
        json_data["name"]=data["name"]
        print ("name",json_data["name"])
    if "timestamp" in data:
        json_data["timestamp"]=data["timestamp"]    
        print ("timestamp",json_data["timestamp"])
    if "hearttime" in data:
        json_data["hearttime"]=data["hearttime"]
        print ("hearttime",json_data["hearttime"])

    #三元组
    if "clientId" in data:
        json_data["triad"]["clientId"]=data["clientId"]
        print ("clientId",json_data["triad"]["clientId"])

    if "AccessToken" in data:
        json_data["triad"]["AccessToken"]=data["AccessToken"]
        print ("AccessToken",json_data["triad"]["AccessToken"])

    if "ProjectKey" in data:
        json_data["triad"]["ProjectKey"]=data["ProjectKey"]
        print ("ProjectKey",json_data["triad"]["ProjectKey"])

    # print (json_data)
    with open(cfgpath,'w') as fw:
        fw.write(ujson.dumps(json_data))


def copy_file(src_file, dest_file):
        # 打开源文件以读取
    try:
        with open(src_file, 'r') as src:
            # 打开目标文件以写入（如果文件已存在，这将会覆盖原有内容）
            with open(dest_file, 'w') as dst:
                # 逐行读取并写入到新文件
                for line in src:
                    dst.write(line)
        print(f"文件'{src_file}'已成功复制到'{dest_file}'。")
    except:
        print(f"错误：源文件'{src_file}'不存在。")


def read_file(path):
    result={}
    with open(path,'r') as f:
        data=ujson.load(f)
    # print("json_data",data)
    result = data
    print('!'*30)
    print(path,result)
